package com.example.news.ui;

import static android.content.ContentValues.TAG;
import static java.lang.Thread.sleep;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.media.Image;
import android.os.Bundle;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.news.MainActivity;
import com.example.news.R;
import com.example.news.activity.LoginActivity;
import com.example.news.adapter.NewsDataBindingAdapter;
import com.example.news.bean.NewsBean;

import com.example.news.bean.UserInfo;
import com.example.news.helper.GsonUtils;
import com.example.news.helper.Mp3helper;
import com.example.news.helper.OnItemClickListener;
import com.example.news.helper.Ttshelper;
import com.example.news.helper.UserManage;
import com.example.news.helper.gethttp;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link ListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class ListFragment extends Fragment {

    public Ttshelper tshelper=new Ttshelper();
    public View vi;
    public Context context;//上下文对象
    public String userId;//用户ID
    public  String ip;//后端ip
    public int position=5;//默认播放的新闻下标
    public List<NewsBean> list= new ArrayList<>();//新闻列表
    //获取适配器实例
    NewsDataBindingAdapter stringAdapter = new NewsDataBindingAdapter(getActivity(),list);
    //配置适配器
    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    public int voice=0;//默认的语音合成人声下标
    public Mp3helper mp3helper=null;
    public Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {
                    rvText.setBackground(context.getResources().getDrawable(bg[type]));
                    tshelper.play(context,"当前新闻类别："+typearray[type],voice);
                    Log.i("伏珊瑞。当前新闻类别：", typearray[type]);
                    list.clear();
                    list.addAll(turnjson(msg.obj.toString()));
                    stringAdapter.change(list);
                }
                case 2 :break;
            }
        }
    };
    public Handler handler2=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch(msg.what)
            {
                case 1 : {
                    Log.i(TAG, turnnews(msg.obj.toString()).getText());
                    tshelper.conselplay();
                    try {
                        List<String> a=divideStrByBytes(turnnews(msg.obj.toString()).getText(),145,"UTF-8");
                        for(int i=0;i<a.size();i++)
                        {
                            Log.i(TAG, "序号："+i);
                            tshelper.play(context,a.get(i),voice);
                        }
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }

                }
                case 2 :break;
            }
        }
    };
    public int type;
    public int image;
    public UserInfo userinfo;
    RecyclerView rvText;
    public String typearray[]= {"NBA", "时尚", "军事", "要闻", "股票", "健康", "游戏", "头条"};
    public String typearrayen[]={"sport","fashin","military","mainnews","stock","health","game","headline"};
    public int bg[]= {R.drawable.sport,R.drawable.fashin,R.drawable.military,R.drawable.mainnews,R.drawable.stock,R.drawable.health,
    R.drawable.game,R.drawable.headline};
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";


    private String mParam1;
    private String mParam2;

    public ListFragment() {
        // Required empty public constructor
    }

    public static ListFragment newInstance(String param1, String param2) {
        ListFragment fragment = new ListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view,Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        vi=view;
        ip=this.getString(R.string.ip);
        userId= UserManage.getInstance().getUserInfo(getContext()).getUserName();
        context=getContext();
        try {
            voice =new Random().nextInt(12);
            type=getArguments().getInt("type");
            image=getArguments().getInt("image");
            tshelper.play(context,"当前新闻类别是："+typearray[type]+",点击屏幕将播放新闻，手指左滑播放下一条，手指右滑播放上一条；手指上滑播放上一类别，手指下滑播放下一类别；",voice);
            initView();
            getnews(typearray[type]);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_list, container, false);
    }
    private void initView() throws InterruptedException {
        rvText = vi.findViewById(R.id.news);
         stringAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int newsId) {
                try {
                    position=newsId;
                    voice =new Random().nextInt(12);
                    Log.i(TAG, list.get(newsId).getNewsId());
                    userinfo=UserManage.getInstance().getUserInfo(getContext());
//                    addreadtype(userinfo.getUserName(),typearrayen[type]);
                    getnewsByid(list.get(newsId).getNewsId());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        rvText.setAdapter(stringAdapter);
        rvText.setLayoutManager(linearLayoutManager);
        //配置布局管理器
    }
    public void getnews(String type) throws InterruptedException {
        String url="http://"+ip+":8080/news/getNewsbytype?type="+type;
        gethttp ghttp=new gethttp(url,handler);
        ghttp.start();
        ghttp.join();
    }
    public void getnewsByid(String newsId) throws InterruptedException {
        SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        int a=sp.getInt("readcount",-1);
        SharedPreferences.Editor edit = sp.edit();
        edit.remove("readcount");
        edit.putInt("readcount", a+1);
        edit.commit();
        String url="http://"+ip+":8080/news/getNewsbyid?newsId="+newsId+"&userId="+userId;
        gethttp ghttp=new gethttp(url,handler2);
        ghttp.start();
        ghttp.join();
    }
    public void addreadtype(String userid,String type) throws InterruptedException {
        String url="http://"+ip+":8080/user/addreadtype?userid="+userid+"&type="+type;
        gethttp ghttp=new gethttp(url,handler);
        ghttp.start();
        ghttp.join();
    }
    public void tos(String line)
    {
        Toast.makeText(getContext(), line, Toast.LENGTH_SHORT).show();
    }
    public List<NewsBean> turnjson(String line)
    {
        GsonUtils util = new GsonUtils();
        return util.parse2Objects(line,NewsBean.class);
    }
    public NewsBean turnnews(String line)
    {
        GsonUtils util = new GsonUtils();
        return util.fromJson(line,NewsBean.class);
    }
    public static final List<String> divideStrByBytes(String str, int len, String charSet) throws UnsupportedEncodingException, UnsupportedEncodingException {
        List<String> strSection = new ArrayList<>();
        byte[] bt = str.getBytes(charSet);
        int strLen = bt.length;
        int startPos = 0;
        int startStrPos = 0;
        while (startPos < strLen) {
            Integer subSectionLen = len;
            if (strLen - startPos < len) {
                subSectionLen = strLen - startPos;
            }
            byte[] br = new byte[subSectionLen];
            System.arraycopy(bt, startPos, br, 0, subSectionLen);
            String res = new String(br, charSet);
            int resLen = res.length();
            if (str.substring(startStrPos, startStrPos + resLen).getBytes(charSet).length > len) {
                res = res.substring(0, resLen - 1);
            }
            startStrPos += res.length();
            strSection.add(res);
            startPos += res.getBytes(charSet).length;
        }
        return strSection;
    }
    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {

            }
        };
    }

    public void showToast(String text) {
        Toast.makeText(getActivity(), text, Toast.LENGTH_SHORT).show();
    }
    private float lastTouchX;
    private float lastTouchY;
    // 实现回调接口，定义触摸后的操作
    private MainActivity.MyTouchListener myTouchListener = new MainActivity.MyTouchListener() {

        @Override
        public void onTouch(MotionEvent ev) {
            tshelper.conselplay();

            switch (ev.getAction()) {
                // 手指点击屏幕时，记录当前的X坐标和Y坐标
                case MotionEvent.ACTION_DOWN:
                    lastTouchX = ev.getX();
                    lastTouchY = ev.getY();
                    break;
                /*
                 * 手指在屏幕上滑动的时候，获取当前的X坐标和Y坐标，然后和起始位置的坐标做对比，
                 * 如果移动的距离超过1，显示该图片
                 */
                case MotionEvent.ACTION_MOVE:
                    float disX = ev.getX() - lastTouchX;
                    float disY = ev.getY() - lastTouchY;
                    Log.i(TAG, "onTouch: Y="+disY);
                    Log.i(TAG, "onTouch: X="+disX);
                    if (disX <- 200) {
                        try {
                            tshelper.conselplay();
                            mp3helper=new Mp3helper(getContext(),R.raw.nextone);
                            if(position==list.size()-1) position=-1;
                            getnewsByid(list.get(++position).getNewsId());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else if(disX >200){
                        try {
                            tshelper.conselplay();
                            mp3helper=new Mp3helper(getContext(),R.raw.lastone);
                            if(position==0) position=list.size();
                            getnewsByid(list.get(--position).getNewsId());
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else if(disY>350){
                        tshelper.conselplay();
                        if(type==0) type=typearray.length;
                        try {
                            voice =new Random().nextInt(12);

              ;
                            getnews(typearray[--type]);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }else if(disY <-350){
                        tshelper.conselplay();
                        if(type==typearray.length-1) type=-1;
                        try {
                            voice =new Random().nextInt(12);
                            getnews(typearray[++type]);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                    break;
                default:tshelper.conselplay();
                    break;
            }
        }
    };
    @Override
    public void onResume() {
        super.onResume();
        // 在onResume里面注册回调
        ((MainActivity) this.getActivity())
                .registerMyTouchListener(myTouchListener);
    }

    @Override
    public void onStop() {
        tshelper.conselplay();
        super.onStop();
    }
}